//
//  StockAppDelegate.m
//  Stock
//
//  Created by blacksun on 11-6-5.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "StockAppDelegate.h"
#import "RootViewController.h"

@implementation StockAppDelegate


@synthesize window=_window;
@synthesize stockSections;
@synthesize stockAppService;
@synthesize pushToken;
@synthesize rootViewController;

@synthesize navigationController=_navigationController;


#pragma mark -Service Delegate
-(void)requestFinishedWithResult:(id)aResult andUserinfo:(NSDictionary *)aUserinfo{
    retryCount = 1;
    StockContext *context = [StockContext shareInstance];
    context.sections = aResult;
    NSString *action = [aUserinfo objectForKey:kASIHttpRequestUserinfoKey];
    if ([kStockAppServiceSignUp isEqualToString:action]) {
        if (self.pushToken && [StockContext shareInstance].userId) {
            [self.stockAppService sendPushToken:pushToken];
        }
    }
    //NSLog(@"request finished:1");
    [rootViewController updateNotifyMessage:1];
}
-(void)requestFinishedwithError:(NSError *)aError andUserinfo:(NSDictionary *)aUserinfo{
    if (retryCount<3) {
        [self updateRemoteData];
        retryCount ++;
        return;
    }
    //NSLog(@"%@ error",[aUserinfo objectForKey:kASIHttpRequestUserinfoKey]);
    if ([aError code]==1) {
        //NSLog(@"request error:3");
        [rootViewController updateNotifyMessage:3];//network unavalable;
    }else{
        NSLog(@"request error:2");
        //[rootViewController updateNotifyMessage:2];
    }
}

-(void)updateRemoteData{
    
    [rootViewController updateNotifyMessage:0];
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *userId = [userDefault objectForKey:kUserIdInUserDefault];
    //NSLog(@"%@",userId);
    if (userId) {
        [stockAppService loginWithUserId:userId];
        [StockContext shareInstance].userId = userId;
    }else{
        [stockAppService signUp];
    }
    //NSLog(@"update:0");
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    [MobClick setDelegate:self];
    [MobClick appLaunched];
    
    [[StockAppHelper shareInstance] createTables];
    
    MyStock *mystock = [[[MyStock alloc] init] autorelease];
    ReadStatus *readStatus = [[[ReadStatus alloc] init] autorelease];
    [mystock save];
    [readStatus save];
    [mystock deleteObject];
    [readStatus deleteObject];
    
    NSString *path = [[CommonUtil shareInstance] pathOfResouceInMainBundle:@"kStocks.plist"];
    NSArray *tempStockSections = [[NSArray alloc] initWithContentsOfFile:path];
    self.stockSections = tempStockSections;
    [tempStockSections release];
    self.window.rootViewController = self.navigationController;
    [self.window makeKeyAndVisible];
    
    self.stockAppService = [[[StockAppService alloc] initWithDelegate:self] autorelease];
    
    [self updateRemoteData];
    
    //NSLog(@"Registering for push notifications...");    
    [[UIApplication sharedApplication] 
     registerForRemoteNotificationTypes:
     (UIRemoteNotificationTypeAlert | 
      UIRemoteNotificationTypeBadge | 
      UIRemoteNotificationTypeSound)];
    application.applicationIconBadgeNumber = 0; //程序开启，设置UIRemoteNotificationTypeBadge标识为0
    
    NSDictionary *remoteUserInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if ([[remoteUserInfo objectForKey:@"type"] isEqualToString:@"StockMonitor"]) {
        NSString *stockId = [remoteUserInfo objectForKey:@"stockId"];
        int direction = [[remoteUserInfo objectForKey:@"direction"] intValue];
        StockRadar *radar = [StockRadar findByStockId:stockId andType:direction];
        if (!radar.repeat) {
            radar.status = 1;
        }
        NSLog(@"remote nofity");
        radar.lastDate = [NSDate dateWithTimeIntervalSinceNow:1];
        [radar save];
    }
    
    
    return YES;
}

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { 
    NSString *token = [NSString stringWithFormat:@"%@",deviceToken];
    token = [token stringByReplacingOccurrencesOfString:@"<" withString:@""];
    token = [token stringByReplacingOccurrencesOfString:@">" withString:@""];
    self.pushToken = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"token=%@",pushToken);
    if ([StockContext shareInstance].userId) {
        [self.stockAppService sendPushToken:pushToken];
    }
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err { 
    
    NSString *str = [NSString stringWithFormat: @"Error: %@", err];
    NSLog(@"%@",str);    
    
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    if ([[userInfo objectForKey:@"type"] isEqualToString:@"StockMonitor"]) {
        NSString *stockId = [userInfo objectForKey:@"stockId"];
        int direction = [[userInfo objectForKey:@"direction"] intValue];
        StockRadar *radar = [StockRadar findByStockId:stockId andType:direction];
        if (!radar.repeat) {
            radar.status = 1;
        }
        radar.lastDate = [NSDate dateWithTimeIntervalSinceNow:1];
        [radar save];
    }
    /*for (NSString* key in userInfo) {
        NSLog(@"key: %@, value: %@", key, [userInfo objectForKey:key]);
    } */   
    
}



- (void)applicationWillResignActive:(UIApplication *)application
{
    [MobClick appTerminated];
}

- (void)applicationDidEnterBackground:(UIApplication *)application{
    [self.stockAppService logout];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    //NSLog(@"will foreground");
    [MobClick appLaunched];
    [self.navigationController popToRootViewControllerAnimated:NO];
    [self updateRemoteData];
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
   // NSLog(@"did active");
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    [MobClick appTerminated];
}

-(NSString*)appKey{
    return @"4eaa9dbb5270156244000018";
}

- (void)dealloc
{
    [_window release];
    [_navigationController release];
    [stockSections release];
    [stockAppService cancleAllRequest];
    [stockAppService release];
    [pushToken release];
    [rootViewController release];
    [super dealloc];
}

@end